<template>
  <div>
    <!-- this.$ref.multipleTable.selection -->
    <el-table
      ref="checkTable"
      :data="tableData"
      border
      style="width: 100%"
      empty-text="你的购物车空空如也，快去选书吧！"
      @selection-change="selected"
    >
      <el-table-column type="selection" width="50"> </el-table-column>
      <el-table-column label="封面" width="200" align="center">
        <template scope="scope">
          <div>
            <img :src="scope.row.book.image" style="height: 50px;width: 50px" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" width="300" align="center">
        <template scope="scope">
          <div>
            <span style="font-size: 18px;padding-left: 20px;">{{
              scope.row.book.name
            }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="单价"
        width="150"
        prop="book.price"
        align="center"
      >
      </el-table-column>
      <el-table-column label="数量" width="200" align="center">
        <template scope="scope">
          <div>
            <el-input
              v-model="scope.row.num"
              @change="handleInput(scope.row, this.$refs.checkTable.selected)"
            >
              <el-button slot="prepend" @click="del(scope.row, scope.$index)"
                ><i class="el-icon-minus"></i
              ></el-button>
              <el-button slot="append" @click="add(scope.row)"
                ><i class="el-icon-plus"></i
              ></el-button>
            </el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="小计" width="150" prop="price" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template scope="scope">
          <el-button
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除<i class="el-icon-delete2 el-icon--right"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-button @click="checkout()" type="primary" style="float: right">{{
      "商品总额：" + moneyTotal
    }}</el-button>
  </div>
</template>

<script>
import { getRequest, myPostRequest } from "../utils/api";
import { putRequest } from "../utils/api";
import { deleteRequest } from "../utils/api";
import { postRequest } from "../utils/api";
export default {
  // 依赖注入
  inject: ['reload'],
  data() {
    return {
      tableData: [
        {
          book: {
            id: 1,
            image: "http://i1.mifile.cn/a1/pms_1474859997.10825620!80x80.jpg",
            name: "小米手环2",
            price: 199
          },
          price: 149,
          num: 1,
        //   goodTotal: 149
        },
      ],
      moneyTotal: 0,
      multipleSelection: [],
      orderInfo: {}
    };
  },
  mounted: function () {
      this.loading = true;
      this.initCart();
      this.loading = false;
  },
  methods: {
    initCart() {
        this.orderInfo = {}
        this.tableData = []
        this.moneyTotal = 0
        var _this = this;
        getRequest('cart/getcart?user_id=' + _this.$store.state.userId).then(
          resp => {
              if(resp.data.code == 0) {
                  let data = resp.data.data;
                  _this.orderInfo = data.order_info;
                  _this.tableData = data.items;
                  _this.moneyTotal = data.orderInfo.price;
              } else {
                  _this.$message.error('服务器繁忙，稍后再试');
              }
          }
      );
    },

    handleDelete(index, row) {
          //删除数组中指定的元素
        postRequest('cart/delete', {
                item_id:row.id
            }).then(
                resp => {
                    if(resp.data.code == 0) {
                        this.tableData.splice(index,1);
                        this.handleInput(row,this.$refs.checkTable.selection);
                        this.$message({
                            type: 'success',
                            message: '删除成功！'
                        });
                    } else {
                        this.$message.error('删除失败！');
                    }
                }
            )
        // .catch(() => {
        //   this.$message({
        //     type: "info",
        //     message: "已取消删除"
        //   });
        // });
    },
    handleInput: function(value, selection){
      var _this = this;
      if (null == value.num || value.num == "") {
        value.num = 1;
      }
      value.price = (value.num * value.book.price).toFixed(2); //保留两位小数
      //增加商品数量也需要重新计算商品总价
      this.selected(selection);

    },
    add: function(addGood) {
      //输入框输入值变化时会变为字符串格式返回到js
      //此处要用v-model，实现双向数据绑定
      let _this = this;
      postRequest('cart/changenum', {
          item_id:addGood.id,
          num:1
      }).then(
          resp => {
              if(resp.data.code == 0) {
                if (typeof addGood.num == "string") {
                  addGood.num = parseInt(addGood.num);
                }
                addGood.num += 1;
                this.handleInput(addGood,this.$refs.checkTable.selection);
              }else {
                _this.$message.warning('修改商品数量失败！');
              }
          }
      )
    //   this.$options.methods.handleInput(addGood,this.$refs.checkTable.selection);
    //   console.log(this.$refs);
    //   console.log(this.$refs.checkTable.selection);

    },
    del: function(delGood,index) {
        // console.log(delGood);
        // console.log(index);
      if (typeof delGood.num == "string") {
        delGood.num = parseInt(delGood.num);
      }

      let _this = this;

      if(delGood.num > 1) {
          postRequest('cart/changenum', {
            item_id:delGood.id,
            num:-1
          }).then(
            resp => {
                if(resp.data.code == 0) {
                    delGood.num -= 1;
                    this.handleInput(delGood,this.$refs.checkTable.selection);
                } else {
                    _this.$message.warning('修改商品数量失败!');
                }
            }
          );
      } else if(delGood.num == 1) {
          this.$confirm("此操作将从购物车中移除此书，是否继续?","提示",{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            postRequest('cart/delete', {
                item_id:delGood.id
            }).then(
                resp => {
                    if(resp.data.code == 0) {
                        this.tableData.splice(index,1);
                        this.handleInput(delGood,this.$refs.checkTable.selection);
                        this.$message({
                            type: 'success',
                            message: '删除成功！'
                        });
                    } else {
                        this.$message.error('删除失败！');
                    }
                }
            )

        })
      }

    },
    //返回的参数为选中行对应的对象
    selected: function(selection) {
        // console.log('selected方法执行了');
      this.multipleSelection = selection;
      this.moneyTotal = 0;
      //此处不支持forEach循环，只能用原始方法了
      for (var i = 0; i < selection.length; i++) {
        //判断返回的值是否是字符串
        if (typeof selection[i].price == "string") {
          selection[i].price = parseInt(selection[i].price);
        }
        this.moneyTotal += selection[i].price;
      }
    },
    // 结算
    checkout() {
        let _this = this;
        var accout = this.moneyTotal;
        if(accout <= 0) {
            this.$message.error('您还没有选中商品！');
            return;
        }

        this.$confirm('确定要提交订单吗？','提示',{
            type: 'primary',
            confirmButtonText: '提交',
            cancelButtonText: '取消'
        })
          .then(() => {
              // 根据接口返回数据
              postRequest('cart/submit', {
                  order_id: _this.orderInfo.id
              }).then(
                  resp => {
                      if(resp.data.code == 0) {
                          _this.$message({
                              message: '提交订单成功!',
                              type: 'success'
                          });
                          _this.initCart();
                      } else {
                          _this.$message.error('提交订单失败！');
                      }
                  }
              )
              this.$message.success('提交成功！');
              // 刷新页面
              this.reload()
          })
          .catch(() => {
              this.$message.warning('已取消提交');
          })
    }
  }
};
</script>

<style></style>
